
let vcodes = []

function genVCode(phone) {
    let re = ''
    for (let i = 0; i < 6; i++) {
        re += parseInt(Math.random() * 10).toString()
    }
    for (let i = 0; i < vcodes.length; i++) {
        if (vcodes[i].data == re) {
            return genVCode()
        }
    }
    vcodes = vcodes.filter(item => {
        return item.phone != phone
    })
    vcodes.push({
        data: re,
        time: new Date(),
        phone
    })
    return re
}

function checkVCode(vcode, phone) {
    vcodes = vcodes.filter(item => {
        if (new Date() - item.time > 1000 * 60 * 10) {
            return false
        }
        return true
    })
    for (let i = 0; i < vcodes.length; i++) {
        if (vcodes[i].data == vcode && vcodes[i].phone == phone) {
            vcodes = [...vcodes.slice(0, i), ...vcodes.slice(i + 1)]
            return true
        }
    }
    return false
}

module.exports = {
    get(phone) {
        return genVCode(phone)
    },
    check(vcode, phone) {
        return checkVCode(vcode, phone)
    }
}